package kr.hyosang.android.penfo.processor;

import java.net.MalformedURLException;
import java.util.List;

import kr.hyosang.HttpUtil;
import kr.hyosang.android.penfo.SharedObject;
import kr.hyosang.android.penfo.parser.Parser;
import android.os.AsyncTask;
import android.util.Log;

public class BaseProcessor<Progress, Result> extends AsyncTask<String, Progress, Result> {
	protected ProcessorListener<Result> listener = null;
	protected Parser<Result> parser;
	private HttpUtil httpUtil;
	
	public BaseProcessor() {
        httpUtil = new HttpUtil();
	}
	
	public void setRequestField(String name, String value) {
	    httpUtil.setRequestProperty(name, value);
	}
	
	
	public void setListener(ProcessorListener<Result> l) {
		listener = l;
	}
	
	public void setParser(Parser<Result> p) {
		parser = p;
	}
	
	public void addPostValue(String name, String value) {
	    httpUtil.addPostValue(name, value);
	}
	
	public String getHeaderField(String name) {
	    return httpUtil.getHeaderField(name);
	}
	
	public List<String> getHeaderFields(String name) {
	    return httpUtil.getHeaderFields(name);
	}
	
	
	
	@Override
	protected void onPreExecute() {
		
	}
	
	@Override
	protected Result doInBackground(String... params) {
		Log.d("penfo", "URL : " + params[0]);
		
		try {
			httpUtil.setURL(params[0]);
			
			SharedObject shared = SharedObject.getInstance();
			
			String cookie = String.format("PHPSESSID=%s; ZBSESSIONID=%s", shared.getPHPSESSID(), shared.getZBSESSIONID());
			
			if(cookie != null && !"".equals(cookie)) {
			    httpUtil.setRequestProperty("Cookie", cookie);
			}
			
			httpUtil.process();
			
			//Set-Cookie 처리
			SharedObject.getInstance().setCookies(httpUtil.getHeaderFields("Set-Cookie"));
			
			String html = httpUtil.getHtml();
			
			return parser.parse(html);
		}catch(MalformedURLException e) {
			e.printStackTrace();
		}catch(NullPointerException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	@Override
	protected void onPostExecute(Result data) {
		if(listener != null) {
			listener.onComplete(data);
		}
	}
	
	@Override
	protected void onCancelled() {
		
		
	}
}
